'use strict';
const Controller = require('egg').Controller;
const ExcelJS = require('exceljs');
const moment = require('moment');
const fs = require('fs');
const path = require('path');
const { mysql } = require('../../config/plugin');

class HomeController extends Controller {


  async account_info() {
    const { ctx } = this;
    const user = await this.getUserInfo();
    ctx.success(user);
  }

  async getUserInfo() {
    const { ctx } = this;
    const { id, username, name, role, role_type, last_login_time } = ctx.user;
    return {
      'userId': id,
      'userName': username,
      'orgId': 2,
      'orgName': name,
      'orgLevel': 1,
      'admin': true,
      last_login_time,
      'menuList': [],
      'resourceUrlList': []
    };
  }

  async account_login() {
    const { ctx } = this;
    const { mysql } = this.app;
    const { password, userName: username } = ctx.request.body;

    const users = await mysql.select('jiaolan_admin_user', {
      where: {
        username,
        password
      },
      limit: 1
    });

    if (users.length === 0) throw new Error('用户名或密码错误');

    const user = users[0];
    ctx.session.user_id = user.id;
    ctx.user = user;
    if (user.role_type < 3) {
      user.user_rights = [ 1000, 1001 ];
    }

    await mysql.update('jiaolan_admin_user', {
      last_login_time: new Date()
    }, {
      where: {
        id: user.id
      }
    });
    const result = await this.getUserInfo();
    ctx.success(result);
  }

  async account_password() {
    const { ctx, app } = this;
    const { mysql } = this.app;
    const { new_password, password } = ctx.request.body;
    const user = ctx.user;

    const users = await mysql.select('jiaolan_admin_user', {
      where: {
        id: user.id,
        password: app.toMd5(password)
      },
      limit: 1
    });

    if (users.length === 0) throw new Error('密码错误');


    await mysql.update('jiaolan_admin_user', {
      password: app.toMd5(new_password)
    }, {
      where: {
        id: user.id
      }
    });
    ctx.success();
  }

  async account_logout() {
    const { ctx } = this;


    ctx.session.user_id = undefined;
    ctx.user = undefined;

    ctx.success();
  }
}

module.exports = HomeController;
